# encoding: utf-8
"""
首页展示部分
"""
from django.http import HttpResponse
from wxxiaohello.models import Blog, Classify, Tag, Comment, Filing
from django.template import Context
from django.shortcuts import render_to_response, RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login as user_login, logout as user_logout
from django.http import  HttpResponseRedirect
from django.core.paginator import Paginator
from django.core.paginator import PageNotAnInteger
from django.core.paginator import EmptyPage
from django.shortcuts import render
from wxxiaohello import jsondump
from django.db import connection
import os
from wxxiaohello.settings import PAGE_SIZE, INDEX_TEMPLATE_DIRS
from select import select
from django.db.models.aggregates import Count
from wxxiaohello.settings import CACHE_PAGE_TIME, MY_SITE_KEY_PREFIX
from django.views.decorators.cache import cache_page
# Create your views here.
# page for index.html and default.html
"""
首页，显示文字列表-带摘要
"""
def index(request):
    return index_pn(request, 1)

@cache_page(CACHE_PAGE_TIME, key_prefix=MY_SITE_KEY_PREFIX)
def index_pn(request, pn):
    '''查询已发布的文章列表，并分页获取查询结果'''
    blogs = Blog.objects.filter(release=1).order_by("-id")
    paginator = Paginator(blogs, PAGE_SIZE)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
    '''查询文章的标签'''
    for blog in blog_list:
        blog.tags = blog.tag.all()
    '''定义返回值格式'''
    context = Context({
                       "blog_list":blog_list,
                       "query":"/index/",
                       "title":"首页",
                       })

    return render(request, INDEX_TEMPLATE_DIRS + "index.html", context)

"""
文章内容页面
"""
@cache_page(CACHE_PAGE_TIME, key_prefix=MY_SITE_KEY_PREFIX)
def blog(request, blog_id):
    try:
        blog = Blog.objects.get(id=blog_id)
        blog.tags = blog.tag.all()
        ''''取上一条和下一条数据'''
        try:
            nextBlog = Blog.objects.filter(id__lt=blog_id).filter(release=1).order_by("-id")[0]
        except:
            nextBlog = None
        try:
            preBlog = Blog.objects.filter(id__gt=blog_id).filter(release=1).order_by("id")[0]
        except:
            preBlog = None
        blog.preBlog = preBlog
        blog.nextBlog = nextBlog
        '''该文章的评论'''
        comments = Comment.objects.filter(blog_id=blog_id).order_by("-id")
        blog.comments = comments
        title = blog.title
    except:
        blog = None
        title = "None"
        
    context = Context({
                       "blog":blog,
                       "title":title,
                       })
  
    return render(request, INDEX_TEMPLATE_DIRS + "blog.html", context)

"""
根据  tag_id 查询 文章
"""
def tag_blog(request, tag_id):
    return tag_blog_pn(request, tag_id, 1)

@cache_page(CACHE_PAGE_TIME, key_prefix=MY_SITE_KEY_PREFIX)
def tag_blog_pn(request, tag_id, pn):
    '''如果tag_id不存在，则默认tag内容为none'''
    tagcontent = "none"
    try:
        tag = Tag.objects.get(id=tag_id)        
        blogs = tag.blog_set.all().order_by("-id")
        paginator = Paginator(blogs, PAGE_SIZE)
        try:
            blog_list = paginator.page(pn)
        except PageNotAnInteger:
            blog_list = paginator.page(1)
        except EmptyPage:
            blog_list = paginator.page(paginator.num_pages)
            
        for blog in blog_list:
            blog.tags = blog.tag.all()
        tagcontent = tag.content
    except:
        blog_list = None

    context = Context({
                       "blog_list":blog_list,
                       "query":"/tag/" + str(tag_id) + "/",
                       "title":"标签-" + str(tagcontent.encode("utf-8")),
                       })
    
    return render(request, INDEX_TEMPLATE_DIRS + "index.html", context)


"""
根据  classfy_id  分组ID 查询 文章
"""
def group_blog(request, classify_id):
    return group_blog_pn(request, classify_id, 1)

@cache_page(CACHE_PAGE_TIME, key_prefix=MY_SITE_KEY_PREFIX)
def group_blog_pn(request, classify_id, pn):
    blogs = Blog.objects.filter(classify_id=classify_id).order_by("-id")
    paginator = Paginator(blogs, PAGE_SIZE)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
        
    for blog in blog_list:
        blog.tags = blog.tag.all()
    '''获取分组名字，如果为空，则为none，此为默认值'''
    classifycontent = "none"
    try:
        classify = Classify.objects.get(id=classify_id)
        classifycontent = classify.content
    except:
        classifycontent = "none"

    context = Context({
                       "blog_list":blog_list,
                       "query":"/group/" + str(classify_id) + "/",
                       "title":"分类-" + str(classifycontent.encode("utf-8")),
                       })
    
    return render(request, INDEX_TEMPLATE_DIRS + "index.html", context)

"""
根据  输入的关键词 在标题中 查询 文章
"""
# #文章查找
@csrf_exempt
def search(request):
    keyword = request.GET.get('keyword')
    pn = request.GET.get('pn')
    if pn is None:
        pn = 1;
    pn = int(pn)
    blogs = Blog.objects.filter(title__contains=keyword.strip()).order_by("-id")
    paginator = Paginator(blogs, PAGE_SIZE)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
    
    for blog in blog_list:
        blog.tags = blog.tag.all()

    context = Context({
                       "blog_list":blog_list,
                       "query":"/search/?keyword=" + keyword + "&pn=",
                       "title":"搜索-" + keyword.encode("utf-8"),
                       })
    
    return render(request, INDEX_TEMPLATE_DIRS + "index.html", context)

@csrf_exempt
def login(request):
    
    '''登陆后的默认跳转地址'''
    redirect_to = "/edit"
    if request.user.is_authenticated():
        return  HttpResponseRedirect(redirect_to) 
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                        user_login(request, user)
                        return HttpResponseRedirect(redirect_to) 
            else:
                    return render_to_response("login.html", {"message":"用户没有启用！"}, context_instance=RequestContext(request))
        else:
                return render_to_response("login.html", {"message":"账号或密码错误！"}, context_instance=RequestContext(request))
    else:
        return render_to_response('login.html')
    
def logout(request):
    user_logout(request)
    return HttpResponseRedirect('/index.html')

"""
获取文章按年月归档日期列表 - 侧边栏
"""
@csrf_exempt
def filing_list(requests):
    if 'SERVER_SOFTWARE' in os.environ: 
        '''由于sae环境不能使用视图，检测当前为sae环境，则用自定义查询获取归档列表'''
        select = {"month":connection.ops.date_trunc_sql("month", "time")}
        countResults = Blog.objects.extra(select=select).values("month").annotate(number=Count("id")).order_by("-month")
        FILINGS = []
        for obj in countResults:
            dic = {}
            dic['month'] = obj["month"].strftime('%Y-%m')
            dic['count'] = obj["number"]
            FILINGS.append(dic)
        return FILINGS
    else:  
        '''如果不是sae环境，则直接从视图表中获取归档目录列表'''
        filing_list = Filing.objects.all();
        return filing_list.values()

"""
根据  年月 查询 归档的文章
"""
@csrf_exempt
def filing(request, year, month):
    return filing_pn(request, year, month, 1)

@csrf_exempt
@cache_page(CACHE_PAGE_TIME, key_prefix=MY_SITE_KEY_PREFIX)
def filing_pn(request, year, month, pn):
    try:
        blogs = Blog.objects.filter(time__year=year).filter(time__month=month).order_by("-id")
        paginator = Paginator(blogs, PAGE_SIZE)
        try:
            blog_list = paginator.page(pn)
        except PageNotAnInteger:
            blog_list = paginator.page(1)
        except EmptyPage:
            blog_list = paginator.page(paginator.num_pages)
            
        for blog in blog_list:
            blog.tags = blog.tag.all()
    except:
        blog_list = None

    context = Context({
                       "blog_list":blog_list,
                       "query":"/filing/" + str(year) + "/" + str(month) + "/",
                       "title":"归档-" + str(year) + "/" + str(month),
                       })
    
    return render(request, INDEX_TEMPLATE_DIRS + "index.html", context)

"""
根据  classify_id 查询 分组文章数目 - 侧边栏
"""
@csrf_exempt
def group_list(request):
    cursor = connection.cursor()  # 获得一个游标(cursor)对象
    raw_sql = "SELECT wxxiaohello_classify.id as id,  wxxiaohello_classify.content as content ,count(wxxiaohello_blog.id) AS count FROM wxxiaohello_blog, wxxiaohello_classify where wxxiaohello_blog.classify_id = wxxiaohello_classify.id GROUP BY wxxiaohello_blog.classify_id ORDER BY wxxiaohello_classify.id asc"
    cursor.execute(raw_sql)
    fetchall = cursor.fetchall()    
        
    GROUPS = []
    for obj in fetchall:
        dic = {}
        dic['id'] = (obj[0])
        dic['content'] = str(obj[1].encode("utf8"))
        dic['count'] = (obj[2])
        GROUPS.append(dic)
    return GROUPS

"""
获取 侧边栏信息
"""
@cache_page(CACHE_PAGE_TIME, key_prefix=MY_SITE_KEY_PREFIX)
@csrf_exempt
def sidebar(request):
    SIDEBAR = []
    dic = {}
    '''获取分组列表'''
    dic["filing"] = filing_list(request)
    '''获取归档列表'''
    dic["group"] = group_list(request)
    SIDEBAR.append(dic)
    return HttpResponse(jsondump.json_encode(SIDEBAR))

def about(request):
    return render_to_response(INDEX_TEMPLATE_DIRS + 'about.html')

def NF404_viewer(requests):
    return render_to_response('404.html')

def NF500_viewer(requests):
    return render_to_response('404.html')
